import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../stores/user'
import BaseLayout from '../layouts/BaseLayout.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: { title: 'Login' }
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/Register.vue'),
    meta: { title: 'Register' }
  },
  {
    path: '/',
    component: BaseLayout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Home.vue'),
        meta: {
          title: 'Dashboard',
          requiresAuth: true
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: {
          title: 'Profile',
          requiresAuth: true
        }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('../views/Settings.vue'),
        meta: {
          title: 'Settings',
          requiresAuth: true
        }
      },
      {
        path: 'task-list',
        name: 'TaskList',
        component: () => import('../views/student/TaskList.vue'),
        meta: {
          title: 'My Tasks',
          requiresAuth: true
        }
      },
      {
        path: 'task-view',
        name: 'TaskView',
        component: () => import('../views/student/TaskView.vue'),
        meta: {
          title: 'Task View',
          requiresAuth: true
        }
      },
      {
        path: 'project-view',
        name: 'ProjectView',
        component: () => import('../views/student/ProjectView.vue'),
        meta: {
          title: 'My Project',
          requiresAuth: true
        }
      },
      {
        path: 'chat',
        name: 'Chat',
        component: () => import('../views/chat/ChatPage.vue'),
        meta: {
          title: 'Chat',
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/admin',
    component: BaseLayout,
    redirect: '/admin/dashboard',
    meta: {
      requiresAuth: true,
      requiresAdmin: true
    },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('../views/admin/Dashboard.vue'),
        meta: {
          title: 'Admin Dashboard',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('../views/admin/UserManagement.vue'),
        meta: {
          title: 'User Management',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'student-supervisor',
        name: 'StudentSupervisorAssignment',
        component: () => import('../views/admin/StudentSupervisorAssignment.vue'),
        meta: {
          title: 'Student-Supervisor Assignment',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'roles',
        name: 'RoleManagement',
        component: () => import('../views/admin/RoleManagement.vue'),
        meta: {
          title: 'Role Management',
          requiresAuth: true,
          requiresAdmin: true
        }
      },
      {
        path: 'logs',
        name: 'SystemLogs',
        component: () => import('../views/admin/SystemLogs.vue'),
        meta: {
          title: 'System Logs',
          requiresAuth: true,
          requiresAdmin: true
        }
      }
    ]
  },
  {
    path: '/supervisor',
    component: BaseLayout,
    redirect: '/supervisor/dashboard',
    meta: {
      requiresAuth: true,
      requiresSupervisor: true
    },
    children: [
      {
        path: 'dashboard',
        name: 'SupervisorDashboard',
        component: () => import('../views/supervisor/Dashboard.vue'),
        meta: {
          title: 'Supervisor Dashboard',
          requiresAuth: true,
          requiresSupervisor: true
        }
      },
      {
        path: 'students',
        name: 'StudentManagement',
        component: () => import('../views/supervisor/StudentManagement.vue'),
        meta: {
          title: 'Student Management',
          requiresAuth: true,
          requiresSupervisor: true
        }
      },
      {
        path: 'tasks',
        name: 'SupervisorTasks',
        component: () => import('../views/supervisor/ProjectManagement.vue'),
        meta: {
          title: 'Project Management',
          requiresAuth: true,
          requiresSupervisor: true
        }
      },
      {
        path: 'assignments',
        name: 'SupervisorAssignments',
        component: () => import('../views/supervisor/TaskManagement.vue'),
        meta: {
          title: 'Task Management',
          requiresAuth: true,
          requiresSupervisor: true
        }
      },
      {
        path: 'profile',
        name: 'SupervisorProfile',
        component: () => import('../views/supervisor/Profile.vue'),
        meta: {
          title: 'Supervisor Profile',
          requiresAuth: true,
          requiresSupervisor: true
        }
      },
      {
        path: 'chat',
        name: 'SupervisorChat',
        component: () => import('../views/chat/ChatPage.vue'),
        meta: {
          title: 'Chat',
          requiresAuth: true,
          requiresSupervisor: true
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach(async (to, from, next) => {
  console.log('Route navigation started, target path:', to.path)
  const userStore = useUserStore()

  // Initialize user authentication state
  if (!userStore.initialized) {
    console.log('User authentication state not initialized, performing initialization...')
    await userStore.initializeAuth()
  }

  // If authentication is required
  if (to.meta.requiresAuth) {
    console.log('Target path requires login permission')

    // Check if logged in
    if (!userStore.isLoggedIn) {
      console.log('User not logged in, redirecting to login page')
      next('/login')
      return
    }

    // Check for specific role requirements before proceeding, refresh user information to ensure permissions are up-to-date
    if (to.meta.requiresAdmin || to.meta.requiresSupervisor) {
      console.log('Page requires specific role permissions, refreshing user information...')
      try {
        // Attempt to refresh user information, but do not force refresh to avoid possible loops
        // Only force refresh if the actual role does not match the expected role
        let needsForceRefresh = false

        if (to.meta.requiresAdmin && !userStore.isAdmin) {
          console.log('Requires administrator privileges but is not currently an administrator, attempting to force refresh')
          needsForceRefresh = true
        } else if (to.meta.requiresSupervisor && !userStore.isSupervisor) {
          console.log('Requires supervisor privileges but is not currently a supervisor, attempting to force refresh')
          needsForceRefresh = true
        }

        if (needsForceRefresh) {
          await userStore.fetchUserInfo(true)
        }
      } catch (error) {
        console.error('Failed to refresh user information:', error)
      }
    }

    // Check admin permission
    if (to.meta.requiresAdmin && !userStore.isAdmin) {
      console.log('Admin permission required, but user is not admin, redirecting to home page')
      next('/')
      return
    }

    // Check supervisor permission
    if (to.meta.requiresSupervisor && !userStore.isSupervisor) {
      console.log('Supervisor permission required, but user is not supervisor, redirecting to home page')
      next('/')
      return
    }
  }

  // Special handling: redirect supervisor to /supervisor/dashboard when visiting /dashboard
  if (to.path === '/dashboard' && userStore.isSupervisor) {
    console.log('Supervisor visiting /dashboard, redirecting to supervisor dashboard')
    next('/supervisor/dashboard')
    return
  }

  // Set page title
  document.title = `${to.meta.title || 'Home'} - Graduation Project Supervision System`

  // Allow route navigation
  console.log('Route check passed, allowing navigation to:', to.path)
  next()
})

export default router